import tkinter as tk

class AnimationEngine:
    def __init__(self):
        self.animated_widgets = {}
        self.animation_jobs = {}
        
    def register_animated_item(self, widget_id, widget, texture_data, update_callback):
        """注册需要动画的部件"""
        if not texture_data.get('animated', False):
            return
            
        self.animated_widgets[widget_id] = {
            'widget': widget,
            'texture_data': texture_data,
            'update_callback': update_callback,
            'current_frame': 0,
            'frame_count': len(texture_data['frames'])
        }
        
        # 开始动画
        self._schedule_animation_update(widget_id)
        
    def _schedule_animation_update(self, widget_id):
        """安排动画更新"""
        if widget_id not in self.animated_widgets:
            return
            
        data = self.animated_widgets[widget_id]
        frame_time = data['texture_data']['frame_time'] * 100
        
        job_id = data['widget'].after(frame_time, self._update_animation, widget_id)
        self.animation_jobs[widget_id] = job_id
        
    def _update_animation(self, widget_id):
        """更新动画帧"""
        if widget_id not in self.animated_widgets:
            return
            
        data = self.animated_widgets[widget_id]
        
        # 更新帧
        data['current_frame'] = (data['current_frame'] + 1) % data['frame_count']
        texture_data = data['texture_data']
        texture_data['current_frame'] = data['current_frame']
        
        # 更新纹理
        frame_image = texture_data['frames'][data['current_frame']]
        data['update_callback'](frame_image)
        
        # 安排下一次更新
        self._schedule_animation_update(widget_id)
        
    def unregister_animated_item(self, widget_id):
        """取消注册动画部件"""
        if widget_id in self.animation_jobs:
            data = self.animated_widgets[widget_id]
            data['widget'].after_cancel(self.animation_jobs[widget_id])
            del self.animation_jobs[widget_id]
            
        if widget_id in self.animated_widgets:
            del self.animated_widgets[widget_id]
            
    def cleanup(self):
        """清理所有动画"""
        for widget_id in list(self.animation_jobs.keys()):
            self.unregister_animated_item(widget_id)